// pages/venue/room.js
const api = require('../../utils/api');

Page({
  data: {
    venueInfo: {},
    rooms: [],
    currentStoreId:0,
    loading: false,
    selectedTab: 0, // 默认选中第一个类型
    currentTab: 'home', // 当前选中的底部导航项
    currentSwiperIndex: 0, // 当前轮播图索引
    discountInfoList: [],
    tabs: [],
    tabDescriptions: [],
    tabRooms: {},
    bannerImages: [],
    venueFacilities: [],
    currentDate: new Date(),
    timeSlots: [], // 时间段数组
    availableTimeSlots: {},
    bookedTimeSlots: {},
    roomTimelineData: {},
    showNoticeModal: false, // 控制通知弹窗
    noticeContent: '' // 通知内容
  },

  onLoad: function(options) {
    wx.showTabBar();
    // 获取场地ID
    const venueId = options.venueId || 1;
    this.data.currentStoreId = venueId;
    this.setData({
      storeName:wx.getStorageSync('currentStoreName')||'',
      currentStoreId:venueId,
    })
   
  },
  onShow:function(){
    console.log("store onShow");
     // 生成时间段数组
    this.generateTimeSlots();
    this.loadVenueTypes();
    // 加载场地信息和房间列表
    this.loadVenueInfo(this.data.currentStoreId);
  },
  // 生成时间段数组
  generateTimeSlots: function() {
    const now = new Date();
    const currentHour = now.getHours();
    const timeSlots = [];

    // 生成未来24小时的时间段
    for (let i = 0; i < 24; i++) {
      const hour = (currentHour + i) % 24;
      const isNextDay = currentHour + i >= 24;
      const display = isNextDay ? (hour === 0 ? `次日` : `${hour}`) : `${hour}`;
      
      timeSlots.push({
        hour: hour,
        display: display,
        isNextDay: isNextDay,
        index: i // 添加索引，表示从当前小时开始的偏移量
      });
    }

    this.setData({
      timeSlots: timeSlots
    });
  },
  
  // 加载场地信息
  loadVenueInfo: function(venueId) {
    this.setData({ loading: true });
    api.store.getStoreDetail(venueId)
      .then(res => {
        if (res.success && res.data) {
          const venueData = res.data;
          // 处理图片URL
          const bannerImages = venueData.banner ? venueData.banner : [];
          const venueFacilities = venueData.facilities ? JSON.parse(venueData.facilities) : [];
          this.setData({
            venueInfo: venueData,
            bannerImages: bannerImages,
            venueFacilities: venueFacilities,
            loading: false
          });
          // 检查并显示通知
          if (venueData.notice) {
            this.setData({
              showNoticeModal: true,
              noticeContent: venueData.notice
            });
          }
          // 加载房间列表 - 使用currentStoreId保持一致
          this.loadRooms(this.data.currentStoreId,this.data.selectedTab);
        } else {
          wx.showToast({
            title: res.message || '加载场地信息失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('加载场地信息失败', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },
  
  // 加载场地类型
  // 加载场地类型
  loadVenueTypes: function() {
    api.venue.getVenueTypes({ store_id: this.data.currentStoreId })
      .then(res => {
        if (res.success && res.data) {
          const types = res.data.list || [];
          const tabs = types.map(type => ({
            id: type.id,
            name: type.name
          }));
          
          const tabDescriptions = types.map(type => ({
            id: type.id,
            highlightText: type.name,
            normalText: type.description || ''
          }));
          
          this.setData({
            tabs: tabs,
            selectedTab:types[0].id,
            tabDescriptions: tabDescriptions
          });
          
          // 如果有类型，加载第一个类型的房间
          if (types.length > 0) {
            this.loadRooms(this.data.currentStoreId, types[0].id);
          }
        }
      })
      .catch(err => {
        console.error('加载场地类型失败', err);
        wx.showToast({
          title: '加载场地类型失败',
          icon: 'none'
        });
      });
  },
  
  // 加载场地列表
  loadRooms: function(storeId, typeId = 0) {
    this.setData({ loading: true });
    api.store.getStoreVenues(storeId, typeId)
      .then(res => {
        if (res.success && res.data) {
          const rooms = res.data;
          this.setData({
            rooms: rooms,
            loading: false
          });
          
          // 为每个房间加载时间轴数据
          this.loadRoomTimelines(rooms);
        } else {
          wx.showToast({
            title: res.message || '加载房间列表失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('加载房间列表失败', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },
  
  // 加载房间时间轴数据
  loadRoomTimelines: function(rooms) {
    if (!rooms || rooms.length === 0) return;
    
    // 获取当前日期，格式：YYYY-MM-DD
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const todayStr = `${year}-${month}-${day}`;
    
    // 计算次日日期
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tomorrowYear = tomorrow.getFullYear();
    const tomorrowMonth = String(tomorrow.getMonth() + 1).padStart(2, '0');
    const tomorrowDay = String(tomorrow.getDate()).padStart(2, '0');
    const tomorrowStr = `${tomorrowYear}-${tomorrowMonth}-${tomorrowDay}`;
    
    // 初始化时间轴数据对象
    const roomTimelineData = {};
    
    // 对每个房间请求时间轴数据（当天）
    const todayPromises = rooms.map(room => {
      return api.venue.getRoomTimelineData(room.id, todayStr)
        .then(res => {
          if (res.success && res.data) {
            // 处理时间轴数据
            return {
              roomId: room.id,
              timeline: res.data,
              isToday: true
            };
          }
          return null;
        })
        .catch(err => {
          console.error(`加载房间${room.id}的当天时间轴数据失败`, err);
          return null;
        });
    });
    
    // 对每个房间请求时间轴数据（次日）
    const tomorrowPromises = rooms.map(room => {
      return api.venue.getRoomTimelineData(room.id, tomorrowStr)
        .then(res => {
          if (res.success && res.data) {
            // 处理时间轴数据
            return {
              roomId: room.id,
              timeline: res.data,
              isToday: false
            };
          }
          return null;
        })
        .catch(err => {
          console.error(`加载房间${room.id}的次日时间轴数据失败`, err);
          return null;
        });
    });
    
    // 处理所有请求结果
    Promise.all([...todayPromises, ...tomorrowPromises])
      .then(results => {
        // 过滤掉失败的请求
        const validResults = results.filter(result => result !== null);
        
        // 处理每个房间的时间轴数据
        validResults.forEach(result => {
          const { roomId, timeline, isToday } = result;
          
          // 初始化该房间的预约状态（如果尚未初始化）
          if (!roomTimelineData[roomId]) {
            roomTimelineData[roomId] = {};
          }
          
          // 处理时间轴数据
          if (timeline && timeline.slots) {
            const currentHour = today.getHours();
            
            timeline.slots.forEach(slot => {
              // 解析小时数据，确保是数字类型
              const hour = parseInt(slot.hour);
              
              // 如果不是今天的数据，则只处理明天的时间段
              if (!isToday) {
                // 明天的数据：只处理24小时内的数据
                if (hour < currentHour) {
                  // 计算对应的index（从当前时间开始的偏移量）
                  const index = 24 + hour - currentHour;
                  if (index < 24) { // 确保在24小时范围内
                    roomTimelineData[roomId][index] = slot.isBooked;
                  }
                }
              } else {
                // 今天的数据
                if (hour >= currentHour) {
                  // 计算对应的index
                  const index = hour - currentHour;
                  if (index < 24) { // 确保在24小时范围内
                    roomTimelineData[roomId][index] = slot.isBooked;
                  }
                }
              }
            });
          }
        });
        
        console.log('时间轴数据:', roomTimelineData);
        
        // 更新到视图
        this.setData({
          roomTimelineData: roomTimelineData
        });
      });
  },
  
  // 返回上一页
  onTapBack: function() {
    wx.navigateBack();
  },
  
  // 地图导航
  onTapNavigation: function() {
    const { latitude, longitude, name, address } = this.data.venueInfo;
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: name,
      address: address,
      scale: 18
    });
  },
  
  // 拨打电话
  onTapCall: function() {
    const { phone } = this.data.venueInfo;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      });
    }
  },
  
  // 到店指引
  onTapGuide: function() {
    wx.showToast({
      title: '到店指引功能开发中',
      icon: 'none'
    });
  },
  
  // 收藏门店
  onTapFavorite: function() {
    const storeId = parseInt(this.data.currentStoreId); 
    api.user.addFavorite(storeId).then(res => {
      if (res.success) {
        wx.showToast({
          title: '收藏成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: res.message || '收藏失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('添加收藏失败', err);
      wx.showToast({
        title: '网络错误，请稍后再试',
        icon: 'none'
      });
    });
  },
  
  // 切换标签
  onTapTab: function(e) {
    const tabId = e.currentTarget.dataset.id;
    
    // 获取当前选中tab的描述
    const tabDescription = this.data.tabDescriptions.find(item => item.id === tabId);
    
    this.setData({
      selectedTab: tabId
    });
    
    // 加载对应类型的房间
    this.loadRooms(this.data.currentStoreId, tabId);
  },
  
  // 点击房间
  onTapRoom: function(e) {
    const roomId = e.currentTarget.dataset.id;
    const room = this.data.rooms.find(item => item.id === roomId);
    
    // 跳转到时间段选择页面
    wx.navigateTo({
      url: `/pages/venue/timeslot?venueId=${this.data.currentStoreId}&roomId=${roomId}&roomName=${room.name}`
    });
  },

  // 点击开门
  onTapOpenDoor: function() {
    wx.showLoading({
      title: '正在开门...'
    });
    
    // 调用开门API
    api.device.openDoor({
      store_id: this.data.currentStoreId
    })
      .then(res => {
        wx.hideLoading();
        
        if (res.success) {
          wx.showToast({
            title: '开门成功',
            icon: 'success'
          });
          // 震动反馈
          wx.vibrateShort();
        } else {
          wx.showToast({
            title: res.message || '开门失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('开门失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      });
  },

  // 点击续单
  onTapRenew: function() {
    // 检查登录状态
    const app = getApp();
    const userManager = require('../../utils/userManager');
    
    // 使用本地存储判断是否登录，更可靠
    const isLoggedIn = userManager.isLoggedIn();
    console.log('续单检查登录状态:', isLoggedIn, '全局状态:', app.globalData.isLoggedIn);
    
    if (!isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/user/login',
        });
      }, 1000);
      return;
    }
    
    // 跳转到我的订单页面，用户可以选择要续单的订单
    wx.navigateTo({
      url: '/pages/booking/renew',
      fail: (err) => {
        console.error('跳转续单页面失败', err);
        wx.showToast({
          title: '跳转失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 点击验券
  onTapVerifyCoupon: function(e) {
    const type = e.currentTarget.dataset.type;
    // 跳转到验券页面
    wx.navigateTo({
      url: `/pages/coupon/verify?type=${type}&storeName=${this.data.venueInfo.name.replace('【', '').replace('】', '')}`
    });
  },

  // 轮播图切换事件
  onSwiperChange: function(e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    });
  },

  // 点击去充值
  onTapRecharge: function() {
    wx.showToast({
      title: '充值功能开发中',
      icon: 'none'
    });
  },

  // 点击预定按钮
  onTapBookNow: function(e) {
    const roomId = e.currentTarget.dataset.id;
    const room = this.data.rooms.find(item => item.id === roomId);
    
    // 跳转到时间段选择页面
    wx.navigateTo({
      url: `/pages/venue/timeslot?venueId=${this.data.currentStoreId}&roomId=${roomId}&roomName=${room.name}`
    });
  },

  // 切换门店
  onTapSwitchVenue: function() {
    wx.reLaunch({
      url: '/pages/index/index',
      fail: (e) => {
        console.error(e);
      }
    });
  },
  
  // 点击优惠信息
  onTapDiscountItem: function(e) {
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.id;
    
    // 根据类型跳转到不同页面
    switch(type) {
      case 'coupon':
        wx.navigateTo({
          url: `/pages/coupon/detail?id=${id}`
        });
        break;
      case 'activity':
        wx.navigateTo({
          url: `/pages/venue/activity?id=${id}`
        });
        break;
      case 'vip':
        wx.navigateTo({
          url: `/pages/user/vip?id=${id}`
        });
        break;
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
    }
  },

  // 关闭通知弹窗
  onCloseNoticeModal: function() {
    this.setData({ showNoticeModal: false });
  }
});